﻿using System.ComponentModel.DataAnnotations;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Models;
using MediatR;

namespace Core.Identity.Users.Features.Commands.ResetPassword;

#nullable disable

/// <summary>
/// 重置密码
/// </summary>
public class ResetPasswordCommand : IRequest<Result<bool>>
{
    /// <summary>
    /// 用户主键
    /// </summary>
    [Required(ErrorMessage = "用户主键必传")]
    public Guid UserId { get; set; }

    /// <summary>
    /// 新密码
    /// </summary>
    [Required(ErrorMessage = "新密码必传")]
    public required string NewPassword { get; set; }
}
public class ResetPasswordCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<ResetPasswordCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await dbContext.Users.FindAsync(request.UserId, cancellationToken);
        ExceptionHelper.ThrowIfNull(user, "数据不存在");

        user.SetPassword(request.NewPassword);
        dbContext.Users.Update(user);

        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;
        return await Result<bool>.SucceedAsync(result, result, ["重置失败"]);
    }
}
